
//处理首页、贷款超市的产品浏览、申请详情

var source = GetUrlParameter("source");
var phone = GetUrlParameter("phone");
$(function() {
    $(".recommend_loan_list,.list_section").on("click", ".loan_list_cnt", function () {
    	var token = localStorage.getItem("token");
    	//判断用户是否登录
    	if (token == "" || token == null){
    		window.location.href = "login.html";
    	}else{
    		var productid = $(this).attr("productid");
            var productName = $(this).attr("productName");
            goDetail(productid, productName);
    	}
        
    });

});
function ajaxFn(url, parameter, successFn, failFn, type) {
    $.ajax({
        url: url,
        type: type,
        data: parameter,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        xhrFields:{
            withCredentials:true
        },
        success: function (data) {
            successFn(data);
        },
        error: function (err) {
            console.log(err);
            if(failFn && typeof failFn === "function") failFn();
            //showMsg("请求超时，请稍后再试！");
        }
    });
}
var params = {
    "params": {

    }
};

function banner_list() {
    var url = urlLink + "/bCoLoanMarketAd/getPictureAD";
    var paramsStr = JSON.stringify(params);
    ajaxFn(url, paramsStr, bannerListFn, null, "post");
}
function news_list() {
    var url = urlLink + "/bCoLoanMarketAd/getActualAD";
    var paramsStr = JSON.stringify(params);
    ajaxFn(url, paramsStr, newsListFn, null, "post");
}
function product_list(minLimit, maxLimit, multipleValCode, typeValCode) {
    loading();
    var url = urlLink + "/bCoLoanMarketDtl/productList";
    if (minLimit != "" || minLimit != null || maxLimit != "" || maxLimit != null || multipleValCode != "" || multipleValCode !== null
        || typeValCode != "" || typeValCode != null) {
        var params = {
            "params": {
                minLoanLimit: minLimit,
                maxLoanLimit: maxLimit,
                compSort: multipleValCode,
                loanType: typeValCode
            }
        };
    }
    var paramsStr = JSON.stringify(params);
    ajaxFn(url, paramsStr, productListFn, null, "post");
}
function sortList(typeCode) {
    var url = urlLink + "/aSysCodeInfo/getCodeVal";
    if (typeCode != "" || typeCode != null) {
        var params = {
            "params": {
                typeCode: typeCode
            }
        };
    }
    var paramsStr = JSON.stringify(params);
    ajaxFn(url, paramsStr, sortListFn, null, "post");
}
function product_detail(productId) {
    loading();
    var url = urlLink + "/bCoLoanMarketDtl/productDetailed";
    if (productId != "" || productId != null) {
        params.params.id = productId;
    }
    var paramsStr = JSON.stringify(params);
    ajaxFn(url, paramsStr, productDetailFn, null, "post");
}
function bannerListFn(data) {
    console.log(data);
    switch (data.code) {
        case "0000":
        	var url = "http://www.baidu.com";
            var bannerData = data.result;
            var data_length = bannerData.length;
            var bannerHtml = "";
            if (data_length > 0) {
                for (var i=0; i<data_length; i++) {
                    bannerHtml += '<div class="swiper-slide"> ' +
                        '<div class="banner-list"> ' +
                        '<a href='+bannerData[i].adUrl+'>' +
                        '<img src="'+bannerData[i].pictureUrl+'" alt=""  >' +
                        '</a> ' +
                        '</div> ' +
                        '</div>';
                }
            }
            $(".swiper-wrapper").html(bannerHtml);
            var mySwiper = new Swiper('.swiper-container', {
                pagination: '.swiper-pagination',
                loop: true,
                autoplay: 3000,
                autoplayDisableOnInteraction: false
            });
            break;
        default:
            showMsg(data.msg);
            break;
    }
}
function newsListFn(data) {
    switch (data.code) {
        case "0000":
            var newsData = data.result;
            var data_length = newsData.length;
            var newsHtml = "";
            if (data_length > 0) {
                for (var i=0; i<data_length; i++) {
                    newsHtml += "<li>" + newsData[i].comment + "</li>";
                }
            }
            $(".scroll-box ul").html(newsHtml);
            break;
        default:
            showMsg(data.msg);
            break;
    }
}
function productListFn(data) {
    switch (data.code) {
        case "0000":
            var productData = data.result;
            var data_length = productData.length;
            var productHtml = "";
            if (data_length > 0) {
                var sucNum;
                for (var i=0; i<data_length; i++) {
                    if (productData[i].succApplyNum == "" || productData[i].succApplyNum == null) {
                        sucNum = 0;
                    } else {
                        sucNum = productData[i].succApplyNum;
                    }
                    productHtml += "<div class='loan_list_cnt' productid='"+productData[i].id+"' productName='"+productData[i].marketName+"'> " +
                        "<div class='loan_name'> " +
                        "<div class='loan_name_img'><img src='"+productData[i].maPicUrl+"' alt=''> </div> " +
                        "<div class='loan_name_text'> " +
                        "<p class='loan_num'> " +
                        "<span class='loan_num_name'>"+productData[i].marketName+"</span> <span class='loan_num_num'>申请成功 &nbsp;<span>"+sucNum+"</span>人</span></p>" +
                        "<p class='loan_detail'>最高可借 <span>"+productData[i].maxLoanLimit+"元</span> &nbsp;&nbsp;利率最低 <span>"+productData[i].loanRate+"%</span></p>" +
                        "</div>" +
                        "</div>" +
                        "<div class='loan_present'>" +
                        "<span>"+productData[i].slogan+"</span> " +
                        "</div> " +
                        "</div>"
                }
            } else {
                productHtml += "<div class='nullData'><img src='images/null.png' alt=''><p>这里还是空空哒</p></div>"
            }
            $(".recommend_loan_list").append(productHtml);
            $(".list_section").html(productHtml);
            load_over();
            break;
        default:
            showMsg(data.msg);
            break;
    }
}
function goDetail(id, title) {
    window.location.href = "loan_detail.html?id="+ id +"&phone="+ phone +"&source="+ source;
    if (source == "android") {
        var method = "getTitle";  //js调用的android方法名
        var tit = {           //android接收参数，json格式
            "title": title
        };
        callAndroidMethod(method, tit);
    } else if (source == "iOS") {
        window.webkit.messageHandlers.getTitleInfo.postMessage(title);
    }
}

function productDetailFn(data) {
    switch (data.code) {
        case "0000":
            var productData = data.result;
            var loanTerm = productData.prodList;
            var loanTermLen = loanTerm.length;
            var loanTermHtml = "";
            var ope_type = "";
            if (productData) {
                var sucNum;
                $(".detail_name_img img").attr("src", productData.maPicUrl);
                $(".detail_name_name").text(productData.marketName).attr("marketNum", productData.marketNo);
                $(".detail_name_text").attr("chanNum", productData.chanNo);
                $(".detail_rates, .detail_loanrate").text(productData.loanRate +"%");
                $(".detail_loanrate").attr("rate", productData.loanRate);
                if (productData.succApplyNum == "" || productData.succApplyNum == null) {
                    sucNum = 0;
                } else {
                    sucNum = productData.succApplyNum;
                }
                $(".detail_people").text(sucNum);
                $(".detail_limit").text(productData.minLoanLimit +"-"+ productData.maxLoanLimit).attr({"maxLoanLimit": productData.maxLoanLimit, "minLoanLimit": productData.minLoanLimit});
                $(".detail_sum").val(productData.minLoanLimit);
                $(".days_section").text(productData.deadlineInterval);
                $(".apply_term").text(productData.applyData);
                $(".apply_need").text(productData.materialsNeed);
                $(".apply_points").text(productData.applyPoints);
                $(".apply_btn").attr("url", productData.othVisitUrl);

                if (loanTermLen > 0) {
                    for (var x=0; x<loanTermLen; x++) {
                        loanTermHtml += '<li days="'+loanTerm[x].pordDeadline+'">' +
                            '<span class="detail_term">'+loanTerm[x].pordDeadline+'</span> <span class="detail_term_unit">'+loanTerm[x].unit+'</span> ' +
                            '</li>';
                    }
                    $(".lt_bar_panul").html("<li><span class='detail_term'>"+loanTerm[0].pordDeadline+"</span> <span class='detail_term_unit'>"+loanTerm[0].unit+"</span></li>");
                    loadcaculate();
                }
        
                addList(loanTermHtml);
                
                access_count(productData.marketNo, productData.chanNo, "42100001");
            }
            load_over();
            break;
        default:
            showMsg(data.msg);
            break;
    }
}
function sortListFn(data) {
    switch (data.code) {
        case "0000":
            var term_type = data.result.Credit_Type, term_type_length = term_type.length;
            var term_multiple = data.result.Comprehensive_Type, term_multiple_length = term_multiple.length;
            var term_type_html = "", term_multiple_html = "";
            if (term_type_length > 0) {
                for (var i=0; i<term_type_length; i++) {
                    term_type_html += '<li valcode="'+term_type[i].valCode+'">'+term_type[i].valName+'</li>';
                }
                $(".type_sort ul").html(term_type_html);
            }
            if (term_multiple_length > 0) {
                for (var x=0; x<term_multiple_length; x++) {
                    term_multiple_html += '<li valcode="'+term_multiple[x].valCode+'">'+term_multiple[x].valName+'</li>';
                }
                $(".multiple_sort ul").html(term_multiple_html);
            }
            $(".multiple_sort li:first-child, .type_sort li:first-child").addClass("sort_active");
            break;
        default:
            showMsg(data.msg);
            break;
    }
}

// 计算还款总额
function loadcaculate() {
    var sum = parseInt($(".detail_sum").val()),
        rate = parseFloat($(".detail_loanrate").attr("rate")),
        term = parseInt($(".lt_bar_panul .detail_term").text()),
        unit = $(".lt_bar_panul .detail_term_unit").text(),
        maxLoanLimit = parseInt($(".detail_limit").attr("maxloanlimit"));
        //minLoanLimit = parseInt($(".detail_limit").attr("minloanlimit"));
    if ($(".detail_sum").val() == "") {
        sum = 0;
    }
    if (sum > maxLoanLimit) {
        showMsg("额度过高");
        $(".detail_sum").val(maxLoanLimit);
        sum = maxLoanLimit;
    }
    if (unit.indexOf("月") > -1) {
        term = parseInt($(".lt_bar_panul .detail_term").text()) * 30;
    }
    var total = sum + sum * (rate / 100) * term;
    $(".repayment_sum_text").text(total.toFixed(2));
}

// 获取url后的参数
function GetUrlParameter(paramName, arg2) {
    var returnVal = "";
    if (arg2 == undefined) {
        arg2 = '';
    }
    try {
        var paramUrl = window.location.search;
        if (paramUrl.length > 0) {
            paramUrl = paramUrl.substring(1, paramUrl.length);
            var paramUrlArray = paramUrl.split("&");
            for (var i = 0; i < paramUrlArray.length; i++) {
                returnVal = "";
                if (paramUrlArray[i].toLowerCase().indexOf(paramName.toLowerCase()) != -1) {
                    var temp = paramUrlArray[i].split("=");
                    //console.log(temp);
                    if (temp[0].toLowerCase() == paramName.toLowerCase()) {
                        for (var a = 1; a < temp.length; a++) {
                            if (a == (temp.length - 1)) {
                                returnVal += temp[a];
                            } else {
                                returnVal += temp[a] + '=';
                            }
                        }
                        break;
                    }
                } else {
                    returnVal = arg2
                }
            }
        }
    } catch (e) {
    }
    return returnVal;
}
function showMsg(msg) {

    if(!msg) msg = "请求失败，请稍后再试";

    var str = "<div class='information_box'>";
    str += "<div class='information_border'>";
    str += "<div class='information_Info'>";
    str += msg + "</div></div></div>";
    $("body").append(str);
    $(".information_box").fadeIn(500, function () {
        setTimeout(function () {
            $(".information_box").fadeOut(500, function () {
                $(".information_box").remove();
            });
        }, 1500);
    });

}

//调用安卓本地方法
var callAndroidMethod = function(method, params){
    window.jsInterface.invokeMethod(method, [JSON.stringify(params)]);//json对象转成字符串，再转成字符串数组
};
